<template>
    <div class="content">
        <div class="top">
            <ul>
                <li>
                    <SelectIpt :lists="state" ref="state">
                        <p>状态</p>
                    </SelectIpt>
                </li>
                <li>
                    <SelectIpt :lists="role" ref="role">
                        <p>角色</p>
                    </SelectIpt>
                </li>
                <li>
                    <TextIpt ref="employeeName">
                        <p>员工姓名</p>
                    </TextIpt>
                </li>
                <li>
                    <TextIpt ref="phone">
                        <p>手机号</p>
                    </TextIpt>
                </li>
            </ul>
            <div class="btn">
                <el-button type="success" @click="search">查询</el-button>
                <el-button type="primary" @click="adds">新增</el-button>
                <el-upload class="upload-demo" action :on-change="handleChange" :show-file-list="false"
                    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                    :auto-upload="false">
                    <el-button size="small" type="primary">导入</el-button>
                </el-upload>

            </div>
        </div>
        <div class="table">
            <el-table :data="filterEmployee.slice(pages, pages + 8)" border style="width: 100%">
                <el-table-column type="index" width="50" label="序号">
                </el-table-column>
                <el-table-column v-for="column in tableColumns" :key="column.prop" :label="column.label"
                    :width="column.width || null">
                    <template slot-scope="scope">
                        {{ scope.row[column.prop] }}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="open(scope.$index, scope.row)">{{ scope.row.Status == "启用" ? '停用'
                            : '启用' }}</el-button>
                        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" @click='info(scope.$index, scope.row)'>详情</el-button>
                        <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">重置密码</el-button>
                        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">门禁权限</el-button> -->
                        <el-button size="mini" type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="page">
                <div class="total-page">
                    <p>共<span>{{ Math.ceil(emplloyee.length / 8) }}</span>页/<span>{{ emplloyee.length }}</span>条数据</p>
                </div>
                <el-pagination background layout="prev, pager, next,jumper" @current-change="getPage" :page-size=8
                    :total="emplloyee.length">
                </el-pagination>
            </div>
        </div>
        <!-- 编辑弹窗 -->
        <el-dialog title="编辑" center: true :visible.sync="dialogVisible" width="30%" :before-close="handleClose"
            class="dialog">
            <el-form ref="form" :model="form" label-width="80px" :disabled="isShow">
                <el-form-item label="姓名" :rules="{ required: true, message: '姓名不能为空' }" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="手机号" :rules="{ required: true, message: '手机号不能为空' }" prop="phoneNumber">
                    <el-input v-model="form.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item label="证件类型" :rules="{ required: true, message: '证件类型不能为空' }" prop="typeID">
                    <el-select v-model="form.typeID" placeholder="请选择">
                        <el-option v-for="(item, index) in typeID" :key="index" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="证件号" :rules="{ required: true, message: '证件号不能为空' }" prop="cardID">
                    <el-input v-model="form.cardID"></el-input>
                </el-form-item>
                <el-form-item label="角色" :rules="{ required: true, message: '角色不能为空' }" prop="role">
                    <el-select v-model="form.role" placeholder="请选择">
                        <el-option v-for="(item, index) in role" :key="index" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <div class="checked">
                    <p class="checked-title">管辖楼栋</p>
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                        @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="checkedBuild" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="city in builds" :label="city" :key="city">{{ city }}</el-checkbox>
                    </el-checkbox-group>
                </div>
            </el-form>
            <div class="btn" v-show="!isShow">
                <el-button @click="handleClose">取消</el-button>
                <BlueBtn @click.native="onSubmit('form')">确定</BlueBtn>
            </div>
        </el-dialog>
        <!-- 新增弹窗 -->
        <el-dialog title="编辑" center: true :visible.sync="dialogVisible1" width="30%" :before-close="handleClose"
            class="dialog">
            <el-form ref="form1" :model="form1" label-width="80px">
                <el-form-item label="姓名" :rules="{ required: true, message: '姓名不能为空' }" prop="name">
                    <el-input v-model="form1.name"></el-input>
                </el-form-item>
                <el-form-item label="手机号" :rules="[
                    { required: true, message: '手机号不能为空' },
                    { message: '请输入正确的手机号', pattern: /^1[3-9]\d{9}$/, trigger: ['blur', 'change'] }
                ]" prop="phoneNumber">
                    <el-input v-model="form1.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item label="账号" :rules="{ required: true, message: '账号不能为空' }" prop="account">
                    <el-input v-model="form1.account"></el-input>
                </el-form-item>
                <el-form-item label="IC卡号" :rules="{ required: true, message: 'IC卡号不能为空' }" prop="ICNumber">
                    <el-input v-model="form1.ICNumber"></el-input>
                </el-form-item>
                <el-form-item label="证件类型" :rules="{ required: true, message: '证件类型不能为空' }" prop="typeID">
                    <el-select v-model="form1.typeID" placeholder="请选择">
                        <el-option v-for="(item, index) in typeID" :key="index" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="证件号" :rules="{ required: true, message: '证件号不能为空' }" prop="cardID">
                    <el-input v-model="form1.cardID"></el-input>
                </el-form-item>
                <el-form-item label="角色" :rules="{ required: true, message: '角色不能为空' }" prop="role">
                    <el-select v-model="form1.role" placeholder="请选择">
                        <el-option v-for="(item, index) in role" :key="index" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <div class="checked">
                    <p class="checked-title">管辖楼栋</p>
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                        @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="checkedBuild" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="city in builds" :label="city" :key="city">{{ city }}</el-checkbox>
                    </el-checkbox-group>
                </div>
            </el-form>
            <div class="btn" v-show="!isShow">
                <el-button @click="handleClose">取消</el-button>
                <BlueBtn @click.native="onSubmit1('form1')">确定</BlueBtn>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { read, utils } from 'xlsx'; // 使用 import 语法引入 xlsx 库
import TextIpt from '@/components/TextIpt.vue';
import SelectIpt from '@/components/SelectIpt.vue';
import BlueBtn from '@/components/BlueBtn.vue';
export default {
    components: {
        TextIpt,
        SelectIpt,
        BlueBtn
    },
    data() {
        return {
            file: "",
            fileTemp: null,
            //判断哪个数据显示
            isDataShow: true,
            //过滤后的数据
            filterEmployee: [],
            //page
            pages: 0,
            //是否可用
            isShow: false,
            //需要修改数据的ID
            editID: '',
            checkAll: false,
            checkedBuild: [],
            builds: ['单元1', '单元2', '单元3'],
            isIndeterminate: true,
            //弹窗
            dialogVisible: false,
            dialogVisible1: false,
            //编辑
            form: {
                name: '',
                phoneNumber: '',
                role: '',
                typeID: '',
                cardID: '',
                //记录ID
                indexID: ''
            },
            //新增
            form1: {
                name: '',
                phoneNumber: '',
                role: '',
                typeID: '',
                cardID: '',
                account: '',
                ICNumber: ''
            },
            //所有数据
            emplloyee: [],
            //证件类型
            typeID: ['居民身份证', '台湾居民身份证', '军人身份证', '港澳台居民身份证', '台湾居民居住证'],
            //状态
            state: ['启用', '停用'],
            //角色
            role: [],
            tableColumns: [
                // { prop: 'ID', label: '序号', width: 60, },
                { prop: 'Name', label: '姓名', width: 100 },
                { prop: 'Account', label: '账号', width: 160 },
                { prop: 'PhoneNumber', label: '手机号', width: 180 },
                { prop: 'ICCardNumber', label: 'IC卡号', width: 250 },
                { prop: 'RoleName', label: '角色', width: 150 },
                { prop: 'BuildingJurisdiction', label: '管辖楼栋', width: 220 }, // 更改为 Owner 以匹配数据
                { prop: 'Status', label: '状态', width: 120 }, // 更改为 Phone 以匹配数据
                { prop: 'IsLinkedToOperationalAccount', label: '是否关联运营账号', width: 150 } // 更改为 Status 以匹配数据，虽然之前注释中提到不一致，但这里应该是 Status
            ],
        }
    },
    methods: {
        handleChange(file, fileList) {
            this.fileTemp = file.raw;
            if (this.fileTemp) {
                const fileType = this.fileTemp.type;
                if (fileType === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
                    fileType === "application/vnd.ms-excel") {
                    this.importfxx(this.fileTemp);
                } else {
                    this.$message({
                        type: "warning",
                        message: "附件格式错误，请删除后重新上传!",
                    });
                }
            }
        },
        importfxx(obj) {
            console.log("方法importfxx(obj)的参数obj：\n", obj);
            let _this = this;
            this.file = obj;
            var reader = new FileReader();

            reader.onload = (e) => {
                const binary = e.target.result;
                const wb = read(binary, { type: 'binary' });
                const outdata = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                console.log(outdata, "导入数据");

                // 获取 Excel 中的表头列名
                const excelColumns = outdata.length > 0 ? Object.keys(outdata[0]) : [];

                // 确定需要的字段列名
                const requiredColumns = ['姓名', '账号', '手机号', 'IC卡号', '角色', '管辖楼栋', '状态', '是否关联账号', '密码', '证件类型', '证件号'];

                // 检查表头是否包含所有需要的列名
                const hasAllRequiredColumns = requiredColumns.every(col => excelColumns.includes(col));

                if (hasAllRequiredColumns) {
                    // 映射 Excel 数据到符合 el-table 的字段名
                    const mappedData = outdata.map(item => {
                        return {
                            Name: item['姓名'] || '',     // 映射为表格字段名
                            Account: item['账号'] || '',     // 映射为表格字段名
                            PhoneNumber: item['手机号'] || '',  // 映射为表格字段名
                            ICCardNumber: item['IC卡号'] || '',
                            RoleName: item['角色'] || '',
                            BuildingJurisdiction: item['管辖楼栋'] || '',
                            Status: item['状态'] || '',
                            IsLinkedToOperationalAccount: item['是否关联账号'] || '',
                            Password: item['密码'] || '',
                            CardType: item['证件类型'] || '',
                            CardID: item['证件号'] || '',
                        };
                    });

                    // 去重操作：只保留不重复的数据
                    const filteredData = mappedData.filter(newItem => {
                        return !this.filterEmployee.some(existingItem => existingItem.Account === newItem.Account);
                    });

                    // 如果有新的数据
                    if (filteredData.length > 0) {
                        _this.filterEmployee.push(...filteredData);
                       
                        this.importData(filteredData)
                        this.$message({
                            type: "success",
                            message: `成功导入 ${filteredData.length} 条数据！`,
                        });
                    } else {
                        this.$message({
                            type: "warning",
                            message: "没有新的数据需要导入，所有数据已经存在。",
                        });
                    }
                } else {
                    this.$message({
                        type: "warning",
                        message: "Excel 数据的列名不完整，未包含必要的字段（日期、姓名、地址）",
                    });
                }
            };

            reader.readAsBinaryString(this.file);
        },
        //导入数据
        importData(str) {
            this.$axios.post('http://127.0.0.1/employee/importData', {
                str
            },
                {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                        'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                    }
                }).then(res => {

                }).catch(err => {
                    console.log(err);
                })
        },
        //点击查询
        search() {
            const serach = {}

            if (this.$refs.state.value) {
                serach.Status = this.$refs.state.value
            }
            if (this.$refs.role.value) {
                serach.Role = this.$refs.role.value
            }
            if (this.$refs.employeeName.input) {
                serach.Name = this.$refs.employeeName.input
            }
            if (this.$refs.phone.input) {
                serach.PhoneNumber = this.$refs.phone.input
            }
            this.filterEmployee = this.emplloyee.filter(item => {
                // 检查Status是否匹配
                if (serach.Status && item.Status !== serach.Status) {
                    return false; // 如果不匹配，则排除该房间
                }
                if (serach.Role && item.Role !== serach.Role) {
                    return false; // 如果不匹配，则排除该房间
                }

                if (serach.Name && !item.Name.includes(serach.Name)) {
                    return false; // 如果不匹配，则排除该房间
                }

                if (serach.PhoneNumber && !item.PhoneNumber.includes(serach.PhoneNumber)) {
                    return false; // 如果不匹配，则排除该房间
                }
                // 如果所有条件都匹配或为空（表示用户没有为该字段指定筛选条件），则返回true以包含该房间
                return true;

            })

        },
        //新增
        adds() {
            this.getRole()
            this.dialogVisible1 = true
        },
        //get 当前页
        getPage(page) {
            this.pages = 8 * (page - 1)
        },
        //查看详情
        info(index, row) {
            this.handleEdit(index, row)
            this.isShow = true
        },
        //点击编辑弹框的确认
        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.filterEmployee[this.form.indexID].Name = this.form.name
                    this.filterEmployee[this.form.indexID].PhoneNumber = this.form.phoneNumber
                    this.filterEmployee[this.form.indexID].RoleName = this.form.role
                    this.filterEmployee[this.form.indexID].CardType = this.form.typeID
                    this.filterEmployee[this.form.indexID].CardID = this.form.cardID
                    this.filterEmployee[this.form.indexID].BuildingJurisdiction = this.checkedBuild.join(',')
                    this.updata(this.form.name, this.form.phoneNumber, this.form.typeID, this.form.cardID, this.form.role, this.checkedBuild.join(','))

                } else {
                    return false;
                }
            });
        },
        //点击新增弹框的确认
        onSubmit1(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.emplloyee.push({
                        Account: this.form1.account,
                        BuildingJurisdiction: this.checkedBuild.join(','),
                        CardID: this.form1.cardID,
                        CardType: this.form1.typeID,
                        ICCardNumber: this.form1.ICNumber,
                        IsLinkedToOperationalAccount: "是",
                        Name: this.form1.name,
                        PhoneNumber: this.form1.phoneNumber,
                        Role: this.form1.role,
                        Status: '启用'
                    })
                    this.add(this.form1.name, this.form1.phoneNumber, this.form1.typeID, this.form1.cardID, this.form1.role, this.checkedBuild.join(','), this.form1.ICNumber, this.form1.account)

                } else {
                    return false;
                }
            });
        },
        //新增数据
        add(name, num, type, cardID, role, BuildingJurisdiction, IC, account) {
            fetch('http://127.0.0.1/employee/add', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                },
                body: JSON.stringify({
                    name,
                    num,
                    type,
                    cardID,
                    role,
                    BuildingJurisdiction,
                    IC,
                    account
                })
            }).then(res => res.json()).then(res1 => {
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });

                this.dialogVisible1 = false
            }).catch(err => {
                console.log(err)
            })
        },
        //修改数据
        updata(name, num, type, cardID, role, BuildingJurisdiction) {
            fetch('http://127.0.0.1/employee/AllEdit', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                },
                body: JSON.stringify({
                    name,
                    num,
                    type,
                    cardID,
                    role,
                    BuildingJurisdiction,
                    id: this.editID
                })
            }).then(res => res.json()).then(res1 => {
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });

                this.dialogVisible = false
            }).catch(err => {
                console.log(err)
            })
        },
        //复选框的方法
        handleCheckAllChange(val) {
            this.checkedBuild = val ? ['单元1', '单元2', '单元3'] : [];
            this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.builds.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.builds.length;
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    this.dialogVisible = false
                    this.dialogVisible1 = false
                })
                .catch(_ => { });
        },
        //表格的编辑
        handleEdit(index, row) {
            if (row.RoleName == '超级管理员') {
                this.$message.error('该用户不可操作');
                return
            }
            if (!this.role.length) {
                this.getRole()
            }
            if (this.isShow) {
                this.isShow = false
            }
            this.form.name = row.Name
            this.form.phoneNumber = row.PhoneNumber
            this.form.role = row.RoleName
            this.form.typeID = row.CardType
            this.form.cardID = row.CardID
            this.checkedBuild.splice(0, this.checkedBuild.length, ...row.BuildingJurisdiction.split(','))
            this.form.indexID = index + this.pages
            this.editID = row.ID
            this.dialogVisible = true


        },
        handleDelete(index, row) {
            console.log(index, row);
        },
        //修改数据库里的数据
        editData(id, str) {
            fetch('http://127.0.0.1/employee/edit', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头

                },
                body: JSON.stringify({
                    id,
                    str
                })
            }).then(res => res.json()).then(res1 => {
                this.$message({
                    type: 'success',
                    message: '停用(启用)成功!'
                });
            }).catch(err => {
                console.log(err)
            })
        },

        //弹框
        open(index, row) {
            if (row.RoleName == '超级管理员') {
                this.$message.error('该用户不可操作');
                return
            }
            this.$confirm('确认停用(启用)该员工账号吗, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //修改接口里的数据
                this.editData(row.ID, row.Status == "启用" ? '停用' : '启用')
                this.filterEmployee[index].Status = (row.Status == "启用" ? '停用' : '启用')
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //请求所有的数据
        getEmployee() {
            fetch('http://127.0.0.1/employee/all', {
                method: 'GET', // 请求方法
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                }
            }).then(res => res.json()).then(res1 => {
                this.emplloyee = res1
                this.filterEmployee = res1
            }).catch(err => {
                console.log(err);
            })
        },
        // 获取角色分类
        getRole() {
            this.$axios.get('http://127.0.0.1/role/allRole', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                }
            }).then(res => {
                res.data.forEach(item => {
                    this.role.push(item.RoleName)
                    console.log(this.role)
                })
            }).catch(err => {
                console.log(err);
            })
        }
    },
    mounted() {

        this.getEmployee()
        // console.log(this.emplloyee);

    },

}
</script>

<style scoped>
.btn {
    display: flex;
}

.table>>>.el-table {
    min-height: 500px;
}

.page {
    display: flex;
    align-items: center;
    justify-content: end;
    margin-top: 20px;
}

.page>>>button {
    min-width: 35px !important;
    height: 25px;
    line-height: 25px;
    border-radius: 3px !important;
    border: 1px solid rgba(215, 215, 215, 1);
    background: #fff !important;
}

.page>>>.active {
    border-color: rgba(26, 135, 254, 1) !important;
    background-color: rgba(26, 135, 254, 1) !important;
    color: #fff !important;
}

.page>>>.el-pager li {
    min-width: 35px !important;
    height: 25px;
    line-height: 25px;
    border-radius: 3px !important;
    border: 1px solid rgba(215, 215, 215, 1);
    font-size: 12px;
    color: #999;
    font-weight: normal !important;
    background: #fff;
}

.total-page span {
    color: #FF3C2C;
}

.total-page {
    font-size: 12px;
    color: #666;
}

.checked-title {
    font-size: 13px;
    color: #333;
    padding: 10px 0;
    border-bottom: 1px solid #cccccc;
    margin-bottom: 20px;
}

.checked {
    background-color: rgba(240, 243, 248, 1);
    padding: 0 20px 20px;
}

.dialog>>>.el-dialog {
    margin-top: 0 !important;
}

.el-dialog__wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
}

.dialog .btn {
    margin-top: 20px;
    text-align: right;

}

.btn>>>.el-button--default {
    height: 32px;
    width: 94px;
    padding: 0;
    margin-right: 20px;
}

.dialog-title {
    font-size: 14px;
    color: #000;
    padding-bottom: 15px;
    border-bottom: 1px solid #cacaca;
}

/* .table>>>.el-table__row .el-table__cell:nth-of-type(5), */
.table>>>.el-table__row .el-table__cell:nth-of-type(6) {
    color: #3399FF;
    cursor: pointer;
}

.table>>>.cell {
    text-align: center;
}

.table {
    padding: 20px 20px 50px;
    background: #fff;
    border-radius: 4px;
    margin-top: 10px;
}

.top>>>button {
    width: 94px;
    height: 30px;
    margin-right: 20px;
}

.top>>>.el-button {
    line-height: 30px;
    padding: 0;
}

.top {
    background: #fff;
    padding: 20px 35px;
    border-radius: 4px;
}

.top ul {
    display: flex;
}

.top li {
    margin-right: 50px;
    margin-bottom: 20px;
}

p {
    white-space: nowrap;
}

.top li p {
    font-size: 13px;
    color: #666;
}
</style>